import React, { useEffect, useState, useImperativeHandle, forwardRef, useRef } from 'react';
import { Alert, Spin } from 'antd';
import $http from '@/services/http.service.v2';
import $wss from '@/services/wss.service';
import $helper from '@/services/helper.service';
import useAppStore from '@/store/useAppStore';

export default forwardRef(function WssLogs(props, ref) {
  const [loading, setLoading] = useState(false)
  const [list, setList] = useState([])
  const logScrollLocked = useAppStore(state => state.logScrollLocked)
  const autoScrollTimer = useRef()
  const scrollEleRef = useRef()
  useEffect(() => {
    autoScrollTimer.current = setInterval(() => {
      if (logScrollLocked) return
      if (!scrollEleRef.current) return
      scrollEleRef.current.scrollTop = scrollEleRef.current.scrollHeight
    }, 500);
    return () => {
      autoScrollTimer.current && clearInterval(autoScrollTimer.current)
    }
  }, [logScrollLocked])

  useEffect(() => {
    setLoading(true)
    $http.getLogs().subscribe(res => {
      setLoading(false)
      setList(res.data.list)
    })
  }, [])
  useEffect(() => {
    $wss.on("log", handleNewLog, "WssLogs")
    return () => {
      $wss.off("log", handleNewLog, "WssLogs")
    }
  }, [list])
  function handleNewLog(event) {
    setList(list => [...list, {id: $helper.uuid(), ...event.data.data}])
  } 
  useImperativeHandle(ref, () => ({
    clear: () => {
      setLoading(true)
      $http.clearLogs().subscribe(res => {
        setList([])
        setLoading(false)
      })
    },
  }));
  return (
    <div ref={scrollEleRef} className="scroll-ele-wrapper">
      {loading ? (
        <div className="flex items-center justify-center my-12">
          <Spin/>
        </div>
      ) : (
        <div className="wss-logs-wrap">
          {[...list].reverse().map(item => {
            return (
              <Alert key={item.id} className='log-item' message={`${item.content}---${item.created_at}`} type={item.type === 1 ? "success" : "error"}></Alert>
            )
          })}
        </div>
      )}
    </div>
  )
})